const articles = require('../db/articles')
const { QueryTypes } = require('sequelize');
//获取全部文章
exports.getArticles = async function () {
    let results= await articles.sequelize.query(`select * from articles where passing = 1 order by article_id desc`,
    { type: QueryTypes.SELECT });
    
    return results;
}
//根据文章id获取单个文章
exports.getArticleById = async function (id) {
    let results= await articles.sequelize.query(`select * from articles where article_id = '${id}';`,
    { type: QueryTypes.SELECT });
    
    return results;
}

//管理员添加文章
exports.insertArticle = async function (title,content) {
    let results= await articles.sequelize.query(`insert articles (title,content,passing) values("${title}","${content}",1)`);
    
    return results;
}

exports.getPageArticles = async function (pageNo) {
    let result;
    let counts;
    if (pageNo>=0) {
        result = await articles.sequelize.query(`select * from articles limit  ${(pageNo-1)*10}, 10;`, { type: QueryTypes.SELECT });
        counts = await articles.sequelize.query("select count(*) as counts from articles ;", { type: QueryTypes.SELECT });
    } else if (pageNo<0) {
        return false;

    }
    return {
        result,
        counts
    };
}


exports.deleteArticleById= async function(article_id){
    const result = await articles.sequelize.query(
        `delete  from articles where article_id = "${article_id}"; `
    );
    return result;
}


//管理员修改文章
exports.updateArticleById = async function (article_id,title,content) {
    let results= await articles.sequelize.query(`update articles set title="${title}",content="${content}",passing=1 where article_id='${article_id}'`);
    
    return results;
}

exports.selectAritlceByTitle = async function (title) {
    let results= await articles.sequelize.query(`select * from articles where title = '${title}'`,
    { type: QueryTypes.SELECT });
    
    return results;
}
